setwd("/home1/30/jc227089/SRE_inv/ran_outs")

source("/home1/30/jc227089/evo-dispersal/SRE_inv/SRE_inv_functions.R")

### initialise ###
args=(commandArgs(TRUE))

#evaluate the arguments
# input arguments will be number of replicates runs (rr), file.ID, spread time (sp), lambda (ld), d.cost (dc), K (K)
for(i in 1:length(args)) {
	 eval(parse(text=args[[i]]))
}

#mother modified to give outputs for parameter space analysis
mother<-function(n=20*40*10, ngens.init=100, gens.breach=1000, spY=20, steps, K=40, lambda, d.cost, mutn=0.05, plot=F, dval=99, spread=0){
	pop<-init.inds(n, 10, spY, hvar=T, dval)
	if (dval<=1) dmut<-FALSE
	else dmut<-TRUE
	maxX<-10+spread+steps+5
	hab<-init.hab(10, spY, 0)	
	nbrs<-neighbours.init(10, spY) #reveal only x up to 10
	for (i in 1:ngens.init){
		if (is.null(pop)==T) return(c(NA, NA, K, lambda, d.cost, spread))
		pop<-repro.disp(pop, hab, 10, spY, K, lambda, d.cost, nbrs, mutn, adap=T, dmut=dmut)
		if (plot==T) plotter(pop, maxX, spY, K)
	}
	nbrs<-neighbours.init(maxX, spY) #reveal all neighbours
	ngens<-ngens.init+spread+gens.breach
	hab<-init.hab(maxX, spY, steps)
	st.time<-0
	for (i in (ngens.init+1):ngens){
		if (is.null(pop)==T) return(c(NA, NA, K, lambda, d.cost, spread))
		pop<-repro.disp(pop, hab, maxX, spY, K, lambda, d.cost, nbrs, mutn, adap=T, dmut=dmut)
		if (plot==T) plotter(pop, maxX, spY, K)
		if (st.time==0 & sum((pop[,"X"])==(10+spread))>0) st.time<-i
		if (max(pop[,"X"])==maxX | i==ngens) {
			b.time<-ifelse(i==ngens, NA, i)
			out<-c(st.time, b.time, K, lambda, d.cost, spread)
			names(out)<-c("start", "breach", "K", "lambda", "d.cost", "spread")
			return(out)
		}
	}
}




sim.result<-c()
for (rep in 1:rr){
	out<-mother(steps=10, lambda=ld, d.cost=dc, plot=F, K=K, spread=sp, gens.breach=3000)
	sim.result<-rbind(sim.result, out)	
}
sim.result<-cbind(rep(sp, rr), sim.result)
save(sim.result, file=paste("SRE_inv_ParSpace", file.ID, ".RData", sep=""))
